/**
 * Created by Administrator on 2017/8/8.
 */
/**
 * Created by Administrator on 2017/2/5.
 */
var CONFIG = require('./config_local.js');
var redis = require('redis'),
    client = redis.createClient(CONFIG.RDS_PORT,CONFIG.RDS_HOST,CONFIG.RDS_OPTS);

var db = {};

client.auth(CONFIG.RDS_PWD, function(){
    console.log('认证通过');
});

client.on('error', function(err){
    console.log('Error : ', err);
});

client.on('connect', function(){
    client.select(CONFIG.TokenRedisDb, function(e, d){
        if(e) {
            console.log(e);
        }
        else if(d == 'OK') {
            console.log('DB['+ CONFIG.TokenRedisDb +'] Redis连接成功！');
        }
    });
});

client.on('end', function(){
    console.log('end');
});

db.set = function(key, value, expire, callback){
    client.set(key, value, function(err, result){
        if(err){
            console.log(err);
            callback(err,null);
            return;
        }

        if(!isNaN(expire) && expire > 0){
            client.expire(key, parseInt(expire));
        }

        callback(null, result);
    });
}

db.get = function (key, callback) {
    client.get(key, function (err, result) {
        if(err){
            console.log(err);
            callback(err, null);
            return;
        }
        callback(null, result);
    });
}

db.mget = function(keys, callback) {
    client.mget(keys, function (err, result) {
        if(err){
            console.log(err);
            callback(err, null);
            return;
        }
        callback(null, result);
    });
}

db.incr = function(key, callback) {
    client.incr(key, function(err, result) {
        if(err){
            console.log(err);
            callback(err, null);
            return;
        }
        callback(null, result);
    });
}

db.expire = function(key, time, callback){
    client.expire(key, time, function(err, result){
        if(err){
            console.log(err);
            callback(err, null);
            return;
        }
        callback(null, result);
    })
}

db.del = function(key, callback) {
    client.del(key , function(err, result){
        if(err){
            console.log(err);
            callback(err, null);
            return;
        }

        callback(null, result);
    });
}

db.select = function(db, callback) {
    client.select(db, function(e, result){
        if(e) {
            console.log(e);
            callback(e, null);
            return;
        }
        callback(null, result);
    })
}

module.exports = db;
